package com.alibaba.ecool.service.impl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.alibaba.ecool.bean.Register;
import com.alibaba.ecool.bean.User;
import com.alibaba.ecool.service.UserLoginService;
import com.alibaba.ecool.service.UserRegisterService;



public class UserRegisterServiceImpl  extends SimpleFormController implements UserRegisterService{
		
	UserLoginService userLoginService;	

		public ModelAndView onSubmit(HttpServletRequest request,
				HttpServletResponse response, Object command, BindException errors)
				throws Exception {
			String method = request.getParameter("method");
			if (method == null || method.equals("init")) {
				return init(command, errors);
			} else if (method.equals("register")) {
				return register(request, response, command, errors);
			} else {
				Register registerForm = (Register) command;
				Map modle = errors.getModel();
				modle.put(getFormSessionAttributeName(), registerForm);
				return new ModelAndView(getSuccessView(), modle);
			}
		}

		public ModelAndView init(Object command, BindException errors)
				throws Exception {
			Register registerForm = (Register) command;
			Map modle = errors.getModel();
			modle.put(getFormSessionAttributeName(), registerForm);
			return new ModelAndView(getFormView(), modle);
		}

		public ModelAndView register(HttpServletRequest request,
				HttpServletResponse response, Object command, BindException errors)
				throws Exception {
			Register register = (Register) command;
			if (!isExist(register)) {
				add(register);
				Map modle = errors.getModel();
				modle.put(getSuccessView(), register);
				response.sendRedirect("login.do");
				return null;
			} else {
				Map modle = errors.getModel();
				modle.put(getFormSessionAttributeName(), register);
				return new ModelAndView(getFormView(), modle);
			}
		}

		public boolean isExist(Register register) {

			if(userLoginService.isExist(register.getUserName())) {
				return true;
			} else {
				return false;
			}
		}

		public void add(Register register) {
			User user = new User();
			user.setUserName(register.getUserName());
			user.setUserPwd(register.getUserPwd());
			user.setEmail(register.getEmail());
			userLoginService.insertUser(user);
		}

		public UserLoginService getUserLoginService() {
			return userLoginService;
		}

		public void setUserLoginService(UserLoginService userLoginService) {
			this.userLoginService = userLoginService;
		}

	

}
